package com.simpd.http_helper;

import java.util.ArrayList;

import org.apache.http.NameValuePair;

import com.simpd.model.NotifikasiSKPD;
import com.simpd.model.SynchronizeConstant;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

public class DownloadingHtmlTask extends AsyncTask<Void, Void, Void> {

	private ProgressDialog dialog;
	private ArrayList<NotifikasiSKPD> notifs;
	private ArrayList<NameValuePair> parameters;

	public DownloadingHtmlTask(ProgressDialog dialog,
		ArrayList<NotifikasiSKPD> notifs, ArrayList<NameValuePair> parameters) {
		this.dialog 	= dialog;
		this.notifs 	= notifs;
		this.parameters = parameters;
	}

	@Override
	protected void onPreExecute() {
		this.dialog.show();
	}

	@Override
	protected Void doInBackground(Void... params) {
		String filePath = null;
		String domain = SynchronizeConstant.SIMPD_DOMAIN;
		String url = null;
		String urlSplit[];
		String downloadUrl = null;
		
		HtmlDownloader htmlDownloader = null;
		
		for (NotifikasiSKPD notif : this.notifs) {
			
			url = notif.getOnlineUrl();
			urlSplit = url.split("/");
			if (notif.getTipeSurat().equalsIgnoreCase(
					SynchronizeConstant.TELAAH)) {
				filePath = SynchronizeConstant.TELAAH_DIR_PATH + ""
						+ urlSplit[urlSplit.length - 1];
			} else if (notif.getTipeSurat().equalsIgnoreCase(
					SynchronizeConstant.SPT)) {
				filePath = SynchronizeConstant.SPT_DIR_PATH + ""
						+ urlSplit[urlSplit.length - 1];
			}
			filePath = filePath + SynchronizeConstant.HTML_EXTENSION;
			downloadUrl = domain + url;
			Log.d("[download-url]", "download url : " + downloadUrl);
			Log.d("[file-path]", "file path : " + filePath);
			htmlDownloader = new HtmlDownloader(downloadUrl, filePath);
			htmlDownloader.setParameter(this.parameters);
			htmlDownloader.isGet(true);
			htmlDownloader.startDownload();
		}
		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		this.dialog.dismiss();
	}

}
